package LeetCode.leetcode735;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;

class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < asteroids.length; i++) {
            boolean alive = true;
            while (asteroids[i] < 0 && !stack.isEmpty() && stack.peek() > 0 && alive) {
                if (stack.peek() > -asteroids[i]) {
                    alive = false;
                }else if (stack.peek() == -asteroids[i]) {
                    stack.pop();
                    alive = false;
                }else {
                    stack.pop();
                }
            }
            if (alive) {
                stack.push(asteroids[i]);
            }
        }
        int[] res = new int[stack.size()];
        for (int i = stack.size() - 1; i >= 0; i--) {
            res[i] = stack.pop();
        }
        return res;
    }
}